package patrol.mobile.com.mobilepatrol.widget;

import android.content.Context;
import android.graphics.Rect;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;

import patrol.mobile.com.mobilepatrol.utils.StringUtils;


/**
 * Created by 健 on 2014/9/16.
 */
public class MyEditText extends AppCompatEditText {
    public double mResult;
    public MyEditText(Context context) {
        super(context);
        if(!isInEditMode())
            initTextListener();
    }

    public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        if(!isInEditMode())
            initTextListener();
    }

    public MyEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        if(!isInEditMode())
            initTextListener();
    }

    private void initTextListener() {
        addTextChangedListener(new TextWatcher() {
            String regex="((^[0-9]+(\\.[0-9]*)?)|(^\\.[0-9]+))(\\+(([0-9]+(\\.[0-9]*)?)|(\\.[0-9]+))?)?";
            CharSequence beforeText;
            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
                beforeText=new StringBuffer(charSequence);
            }
            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if(charSequence.length()>0&&!charSequence.toString().matches(regex)){
                    setText(beforeText);
                }
            }
            @Override
            public void afterTextChanged(Editable editable) {}
        });

    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        updateView(focused);
    }

    private void updateView(boolean focused) {
        String str = getText().toString();
        if(StringUtils.isEmpty(str))
            return;
        if(focused) {
            append("+");
            setSelection(str.length()+1);
        }else if(str.contains("+")){
            String[] strings= str.split("\\+");
            double value=0;
            if(strings.length==2)
                value=getValue(strings[0])+getValue(strings[1]);
            else if(strings.length==1)
                value=getValue(strings[0]);

            setText(value>0?(StringUtils.formatNum(value)+""):"0");

        }
    }

    public double getValue(String str){
        mResult = 0;
        if(!StringUtils.isEmpty(str)&&!str.equals(".")){
            mResult=Double.valueOf(str);
        }
        return mResult;
    }

}
